/*
* @Date: 2021/1/31
* @Author: XueChengwu <xuechengwu@erayt.com>
* @Copyright: 2015-2019 Erayt, Inc.
* @Description: If you have some questions, please contact: xuechengwu@erayt.com.
*/
import { urlEncode } from '../utils/common'

export default store => next => action => {
  if(!action.url || !Array.isArray(action.types)) {
    return next(action)
  }
  const [ LOADING, SUCCESS, ERROR ] = action.types
  next({
    type : LOADING,
    loading: true,
    ...action,
  })
  //组装fetch option
  let url = action.url
  let option = {}
  option.method = action.method?action.method.toUpperCase():'GET'
  if(option.method === 'GET'){
    url += action.params?urlEncode(params).slice(1):''
  }else {
    option.body = JSON.stringify(action.params)
  }
  option.credentials = action.credential?action.credential: 'same-origin'
  action.headers && (option.headers = new Headers(action.headers))
  fetch(action.url, option)
    .then(res => res.json())
    .then(res => {
      next({
        type: SUCCESS,
        loading: false,
        payload: res
      })
      if(action.success) {
        action.success(res, next)
      }
    }).catch(err => {
    next({
      type: ERROR,
      loading: false,
      error: err
    })
    if(action.error) {
      action.error(err, next)
    }
  })
}
